{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Community pipelines"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> **For more information about community pipelines, please have a look at [this issue](https://github.com/huggingface/diffusers/issues/841).**\n",
    "\n",
    "**Community** examples consist of both inference and training examples that have been added by the community.\n",
    "Please have a look at the following table to get an overview of all community examples. Click on the **Code Example** to get a copy-and-paste ready code example that you can try out.\n",
    "If a community doesn't work as expected, please open an issue and ping the author on it.\n",
    "\n",
    "| Example                                | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              | Code Example                                                      | Colab                                                                                                                                                                                                              |                                                     Author |\n",
    "|:---------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------:|\n",
    "| CLIP Guided Stable Diffusion           | Doing CLIP guidance for text to image generation with Stable Diffusion                                                                                                                                                                                                                                                                                                                                                                                                                                   | [CLIP Guided Stable Diffusion](#clip-guided-stable-diffusion)     | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/CLIP_Guided_Stable_diffusion_with_diffusers.ipynb) |             [Suraj Patil](https://github.com/patil-suraj/) |\n",
    "| One Step U-Net (Dummy)                 | Example showcasing of how to use Community Pipelines (see https://github.com/huggingface/diffusers/issues/841)                                                                                                                                                                                                                                                                                                                                                                                           | [One Step U-Net](#one-step-unet)                                  | -                                                                                                                                                                                                                  | [Patrick von Platen](https://github.com/patrickvonplaten/) |\n",
    "| Stable Diffusion Interpolation         | Interpolate the latent space of Stable Diffusion between different prompts/seeds                                                                                                                                                                                                                                                                                                                                                                                                                         | [Stable Diffusion Interpolation](#stable-diffusion-interpolation) | -                                                                                                                                                                                                                  |                    [Nate Raw](https://github.com/nateraw/) |\n",
    "| Stable Diffusion Mega                  | **One** Stable Diffusion Pipeline with all functionalities of [Text2Image](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py), [Image2Image](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py) and [Inpainting](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py) | [Stable Diffusion Mega](#stable-diffusion-mega)                   | -                                                                                                                                                                                                                  | [Patrick von Platen](https://github.com/patrickvonplaten/) |\n",
    "| Long Prompt Weighting Stable Diffusion | **One** Stable Diffusion Pipeline without tokens length limit, and support parsing weighting in prompt.                                                                                                                                                                                                                                                                                                                                                                                                  | [Long Prompt Weighting Stable Diffusion](#long-prompt-weighting-stable-diffusion)                                                                 | -                                                                                                                                                                                                                  |                        [SkyTNT](https://github.com/SkyTNT) |\n",
    "| Speech to Image                        | Using automatic-speech-recognition to transcribe text and Stable Diffusion to generate images                                                                                                                                                                                                                                                                                                                                                                                                            | [Speech to Image](#speech-to-image)                               | -                                                                                                                                                                                                                  | [Mikail Duzenli](https://github.com/MikailINTech)\n",
    "\n",
    "To load a custom pipeline you just need to pass the `custom_pipeline` argument to `DiffusionPipeline`, as one of the files in `diffusers/examples/community`. Feel free to send a PR with your own pipelines, we will merge them quickly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pipe = DiffusionPipeline.from_pretrained(\n",
    "    \"CompVis/stable-diffusion-v1-4\", custom_pipeline=\"filename_in_the_community_folder\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example usages"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### CLIP Guided Stable Diffusion"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "CLIP guided stable diffusion can help to generate more realistic images\n",
    "by guiding stable diffusion at every denoising step with an additional CLIP model.\n",
    "\n",
    "The following code requires roughly 12GB of GPU RAM."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from diffusers import DiffusionPipeline\n",
    "from transformers import CLIPImageProcessor, CLIPModel\n",
    "import torch\n",
    "\n",
    "\n",
    "feature_extractor = CLIPImageProcessor.from_pretrained(\"laion/CLIP-ViT-B-32-laion2B-s34B-b79K\")\n",
    "clip_model = CLIPModel.from_pretrained(\"laion/CLIP-ViT-B-32-laion2B-s34B-b79K\", torch_dtype=torch.float16)\n",
    "\n",
    "\n",
    "guided_pipeline = DiffusionPipeline.from_pretrained(\n",
    "    \"CompVis/stable-diffusion-v1-4\",\n",
    "    custom_pipeline=\"clip_guided_stable_diffusion\",\n",
    "    clip_model=clip_model,\n",
    "    feature_extractor=feature_extractor,\n",
    "    torch_dtype=torch.float16,\n",
    ")\n",
    "guided_pipeline.enable_attention_slicing()\n",
    "guided_pipeline = guided_pipeline.to(\"cuda\")\n",
    "\n",
    "prompt = \"fantasy book cover, full moon, fantasy forest landscape, golden vector elements, fantasy magic, dark light night, intricate, elegant, sharp focus, illustration, highly detailed, digital painting, concept art, matte, art by WLOP and Artgerm and Albert Bierstadt, masterpiece\"\n",
    "\n",
    "generator = torch.Generator(device=\"cuda\").manual_seed(0)\n",
    "images = []\n",
    "for i in range(4):\n",
    "    image = guided_pipeline(\n",
    "        prompt,\n",
    "        num_inference_steps=50,\n",
    "        guidance_scale=7.5,\n",
    "        clip_guidance_scale=100,\n",
    "        num_cutouts=4,\n",
    "        use_cutouts=False,\n",
    "        generator=generator,\n",
    "    ).images[0]\n",
    "    images.append(image)\n",
    "\n",
    "# save images locally\n",
    "for i, img in enumerate(images):\n",
    "    img.save(f\"./clip_guided_sd/image_{i}.png\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `images` list contains a list of PIL images that can be saved locally or displayed directly in a google colab.\n",
    "Generated images tend to be of higher qualtiy than natively using stable diffusion. E.g. the above script generates the following images:\n",
    "\n",
    "![clip_guidance](https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/clip_guidance/merged_clip_guidance.jpg)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### One Step Unet"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The dummy \"one-step-unet\" can be run as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from diffusers import DiffusionPipeline\n",
    "\n",
    "pipe = DiffusionPipeline.from_pretrained(\"google/ddpm-cifar10-32\", custom_pipeline=\"one_step_unet\")\n",
    "pipe()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note**: This community pipeline is not useful as a feature, but rather just serves as an example of how community pipelines can be added (see https://github.com/huggingface/diffusers/issues/841)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Stable Diffusion Interpolation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following code can be run on a GPU of at least 8GB VRAM and should take approximately 5 minutes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from diffusers import DiffusionPipeline\n",
    "import torch\n",
    "\n",
    "pipe = DiffusionPipeline.from_pretrained(\n",
    "    \"CompVis/stable-diffusion-v1-4\",\n",
    "    torch_dtype=torch.float16,\n",
    "    safety_checker=None,  # Very important for videos...lots of false positives while interpolating\n",
    "    custom_pipeline=\"interpolate_stable_diffusion\",\n",
    ").to(\"cuda\")\n",
    "pipe.enable_attention_slicing()\n",
    "\n",
    "frame_filepaths = pipe.walk(\n",
    "    prompts=[\"a dog\", \"a cat\", \"a horse\"],\n",
    "    seeds=[42, 1337, 1234],\n",
    "    num_interpolation_steps=16,\n",
    "    output_dir=\"./dreams\",\n",
    "    batch_size=4,\n",
    "    height=512,\n",
    "    width=512,\n",
    "    guidance_scale=8.5,\n",
    "    num_inference_steps=50,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The output of the `walk(...)` function returns a list of images saved under the folder as defined in `output_dir`. You can use these images to create videos of stable diffusion.\n",
    "\n",
    "> **Please have a look at https://github.com/nateraw/stable-diffusion-videos for more in-detail information on how to create videos using stable diffusion as well as more feature-complete functionality.**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Stable Diffusion Mega"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Stable Diffusion Mega Pipeline lets you use the main use cases of the stable diffusion pipeline in a single class."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#!/usr/bin/env python3\n",
    "from diffusers import DiffusionPipeline\n",
    "import PIL\n",
    "import requests\n",
    "from io import BytesIO\n",
    "import torch\n",
    "\n",
    "\n",
    "def download_image(url):\n",
    "    response = requests.get(url)\n",
    "    return PIL.Image.open(BytesIO(response.content)).convert(\"RGB\")\n",
    "\n",
    "\n",
    "pipe = DiffusionPipeline.from_pretrained(\n",
    "    \"CompVis/stable-diffusion-v1-4\",\n",
    "    custom_pipeline=\"stable_diffusion_mega\",\n",
    "    torch_dtype=torch.float16,\n",
    ")\n",
    "pipe.to(\"cuda\")\n",
    "pipe.enable_attention_slicing()\n",
    "\n",
    "\n",
    "### Text-to-Image\n",
    "\n",
    "images = pipe.text2img(\"An astronaut riding a horse\").images\n",
    "\n",
    "### Image-to-Image\n",
    "\n",
    "init_image = download_image(\n",
    "    \"https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg\"\n",
    ")\n",
    "\n",
    "prompt = \"A fantasy landscape, trending on artstation\"\n",
    "\n",
    "images = pipe.img2img(prompt=prompt, image=init_image, strength=0.75, guidance_scale=7.5).images\n",
    "\n",
    "### Inpainting\n",
    "\n",
    "img_url = \"https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png\"\n",
    "mask_url = \"https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png\"\n",
    "init_image = download_image(img_url).resize((512, 512))\n",
    "mask_image = download_image(mask_url).resize((512, 512))\n",
    "\n",
    "prompt = \"a cat sitting on a bench\"\n",
    "images = pipe.inpaint(prompt=prompt, image=init_image, mask_image=mask_image, strength=0.75).images"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As shown above this one pipeline can run all both \"text-to-image\", \"image-to-image\", and \"inpainting\" in one pipeline."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Long Prompt Weighting Stable Diffusion"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Pipeline lets you input prompt without 77 token length limit. And you can increase words weighting by using \"()\" or decrease words weighting by using \"[]\"\n",
    "The Pipeline also lets you use the main use cases of the stable diffusion pipeline in a single class."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### pytorch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from diffusers import DiffusionPipeline\n",
    "import torch\n",
    "\n",
    "pipe = DiffusionPipeline.from_pretrained(\n",
    "    \"hakurei/waifu-diffusion\", custom_pipeline=\"lpw_stable_diffusion\", torch_dtype=torch.float16\n",
    ")\n",
    "pipe = pipe.to(\"cuda\")\n",
    "\n",
    "prompt = \"best_quality (1girl:1.3) bow bride brown_hair closed_mouth frilled_bow frilled_hair_tubes frills (full_body:1.3) fox_ear hair_bow hair_tubes happy hood japanese_clothes kimono long_sleeves red_bow smile solo tabi uchikake white_kimono wide_sleeves cherry_blossoms\"\n",
    "neg_prompt = \"lowres, bad_anatomy, error_body, error_hair, error_arm, error_hands, bad_hands, error_fingers, bad_fingers, missing_fingers, error_legs, bad_legs, multiple_legs, missing_legs, error_lighting, error_shadow, error_reflection, text, error, extra_digit, fewer_digits, cropped, worst_quality, low_quality, normal_quality, jpeg_artifacts, signature, watermark, username, blurry\"\n",
    "\n",
    "pipe.text2img(prompt, negative_prompt=neg_prompt, width=512, height=512, max_embeddings_multiples=3).images[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### onnxruntime"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from diffusers import DiffusionPipeline\n",
    "import torch\n",
    "\n",
    "pipe = DiffusionPipeline.from_pretrained(\n",
    "    \"CompVis/stable-diffusion-v1-4\",\n",
    "    custom_pipeline=\"lpw_stable_diffusion_onnx\",\n",
    "    revision=\"onnx\",\n",
    "    provider=\"CUDAExecutionProvider\",\n",
    ")\n",
    "\n",
    "prompt = \"a photo of an astronaut riding a horse on mars, best quality\"\n",
    "neg_prompt = \"lowres, bad anatomy, error body, error hair, error arm, error hands, bad hands, error fingers, bad fingers, missing fingers, error legs, bad legs, multiple legs, missing legs, error lighting, error shadow, error reflection, text, error, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry\"\n",
    "\n",
    "pipe.text2img(prompt, negative_prompt=neg_prompt, width=512, height=512, max_embeddings_multiples=3).images[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "if you see `Token indices sequence length is longer than the specified maximum sequence length for this model ( *** > 77 ) . Running this sequence through the model will result in indexing errors`. Do not worry, it is normal."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Speech to Image"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following code can generate an image from an audio sample using pre-trained OpenAI whisper-small and Stable Diffusion.\n",
    "\n",
    "```Python\n",
    "import torch\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "from datasets import load_dataset\n",
    "from diffusers import DiffusionPipeline\n",
    "from transformers import (\n",
    "    WhisperForConditionalGeneration,\n",
    "    WhisperProcessor,\n",
    ")\n",
    "\n",
    "\n",
    "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
    "\n",
    "ds = load_dataset(\"hf-internal-testing/librispeech_asr_dummy\", \"clean\", split=\"validation\")\n",
    "\n",
    "audio_sample = ds[3]\n",
    "\n",
    "text = audio_sample[\"text\"].lower()\n",
    "speech_data = audio_sample[\"audio\"][\"array\"]\n",
    "\n",
    "model = WhisperForConditionalGeneration.from_pretrained(\"openai/whisper-small\").to(device)\n",
    "processor = WhisperProcessor.from_pretrained(\"openai/whisper-small\")\n",
    "\n",
    "diffuser_pipeline = DiffusionPipeline.from_pretrained(\n",
    "    \"CompVis/stable-diffusion-v1-4\",\n",
    "    custom_pipeline=\"speech_to_image_diffusion\",\n",
    "    speech_model=model,\n",
    "    speech_processor=processor,\n",
    "    \n",
    "    torch_dtype=torch.float16,\n",
    ")\n",
    "\n",
    "diffuser_pipeline.enable_attention_slicing()\n",
    "diffuser_pipeline = diffuser_pipeline.to(device)\n",
    "\n",
    "output = diffuser_pipeline(speech_data)\n",
    "plt.imshow(output.images[0])\n",
    "```\n",
    "This example produces the following image:\n",
    "\n",
    "![image](https://user-images.githubusercontent.com/45072645/196901736-77d9c6fc-63ee-4072-90b0-dc8b903d63e3.png)"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 4
}
